<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['el-bottom',index===0?'el-top':'','vCenter']" v-for="(item,index) in scope.row.children" :key="index">
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[index1===0?'':'el-top','vCenter']" v-for="(item1,index1) in item.children" :key="index1">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                        <el-tag
                          type="warning"
                          v-for="(item2,index2) in item1.children"
                          :key="index2"
                          closable
                          @close="removeRightById(scope.row,item2.id)"
                        >
                          {{item2.authName}}
                        </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button icon="el-icon-delete" size="mini" type="danger"@click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button icon="el-icon-setting" size="mini" type="warning" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form label-width="70px" :model="addForm" ref="addFormRef">
        <el-form-item label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input placeholder="请输入角色描述" v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改角色对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form label-width="70px" :model="editForm" ref="editFormRef">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!--树形控件-->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Roles",
    data(){
      return{
        //角色列表
        roleList:[],
        //添加的角色数据
        addForm: {
          roleName:"",
          roleDesc:""
        },
        //添加角色对话框是否弹出
        addDialogVisible: false,
        //修改角色对话框是否弹出
        editDialogVisible:false,
        //分配权限对话框是否弹出
        setRightDialogVisible:false,
        //修改查询的角色数据
        editForm:{},
        //所有权限的数据
        rightList:[],
        //树形控件属性绑定对象
        treeProps: {
          children: 'children',
          label: 'authName'
        },
        //默认选中节点的id值
        defKeys:[],
        //当前即将分配角色权限的id
        roleId:"",
      }
    },
    created() {
      this.getRoleList()
    },
    methods:{
      //获取角色列表
      async getRoleList(){
        const result=(await this.$http.get("roles")).data;
        if(result.meta.status!==200) return this.$message.error("角色列表获取失败");
        this.roleList=result.data;
        console.log(this.roleList)
      },
      //添加角色对话框关闭重置对话框
      addDialogClosed(){
        this.$refs.addFormRef.resetFields();
      },
      //添加新角色
      async addRole() {
        const result = (await this.$http.post("roles", this.addForm)).data;
        if (result.meta.status !== 201) return this.$message.error("添加新角色失败");
        this.$message.success("添加新用户成功");
        this.addDialogVisible = false;
        this.getRoleList();
      },
      //修改查询角色数据
      async showEditDialog(id){
        const result=(await this.$http.get("roles/" + id)).data;
        if(result.meta.status!==200) return this.$message.error("查询用户数据失败");
        this.editForm=result.data;
        this.editDialogVisible=true;
      },
      //修改角色对话框关闭重置对话框
      editDialogClosed(){
        this.$refs.editFormRef.resetFields();
      },
      //修改角色数据
      async editRoleInfo() {
        const result = (await this.$http.put("roles/" + this.editForm.roleId, {
          roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc
        })).data;
        if (result.meta.status !== 200) return this.$message.error("修改数据失败");
        this.$message.success("修改数据成功")
        this.getRoleList();
        this.editDialogVisible = false;
      },
      //删除角色
      removeRoleById(id) {
        //角色确认删除，返回字符串confirm，取消删除，返回字符串cancel
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const result = (await this.$http.delete("roles/" + id)).data;
            if (result.meta.status !== 200) return this.$message.error("删除用户失败");
            this.$message.success('删除成功!');
            this.getRoleList();
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
      },
      //根据id删除对应的权限
      removeRightById(role,rightId){
        //权限确认删除，返回字符串confirm，取消删除，返回字符串cancel
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const result = (await this.$http.delete("roles/" + role.id+"/rights/"+rightId)).data;
            if (result.meta.status !== 200) return this.$message.error("删除权限失败");
            this.$message.success('删除成功!');
            role.children=result.data;
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
      },
      //展示分配权限对话框
      async showSetRightDialog(role){
        this.roleId=role.id;
        //获取所有权限的数据
        const result =(await this.$http.get("rights/tree")).data;
        if(result.meta.status!==200) return this.$message.error("请求权限失败");
        this.rightList=result.data;
        //递归获取三级节点id
        this.getDefKeys(role,this.defKeys);
        this.setRightDialogVisible=true;
      },
      //通过递归的形式，获取已有权限id
      getDefKeys(node,arr){
        //如果当前node节点不包括children属性，则是三级节点
        if(!node.children) {
          return arr.push(node.id);
        };
        node.children.forEach(item=>{
          this.getDefKeys(item,arr)
        })
      },
      //分配权限对话框关闭重置对话框
      setRightDialogClosed(){
        this.defKeys=[];
      },
      //点击为角色分配权限
      async allotRights(){
        const keys=this.$refs.treeRef.getCheckedKeys().concat(this.$refs.treeRef.getHalfCheckedKeys());
        const idStr=keys.join(",");
        const result=(await this.$http.post("roles/" + this.roleId + "/rights", {rids: idStr})).data;
        if(result.meta.status!==200) return this.$message.error("分配权限失败");
        this.$message.error("分配权限成功");
        this.getRoleList();
        this.setRightDialogVisible=false;
      }
    }
  }
</script>

<style scoped lang="less">
  .el-tag {
    margin: 7px;
  }

  .el-top {
    border-top: 1px solid #eee;
  }

  .el-bottom {
    border-bottom: 1px solid #eee;
  }

  .vCenter{
    display: flex;
    align-items: center;
  }
</style>
